﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel.Composition;
using Mysoft.ServerMonitoring.OMKit.ClientServers.ViewModels;
using ProjTemp.Desktop.Common.Utils;
using ProjTemp.Desktop.Common.Controls;
using ProjTemp.Desktop.Common.View;

namespace Mysoft.ServerMonitoring.OMKit.ClientServers.Views
{
    /// <summary>
    /// Interaction logic for ClientServersTreeView.xaml
    /// </summary>
    [Export(typeof(ClientServersTreeView))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public partial class ClientServersTreeView : VBase
    {
        public ClientServersTreeView()
        {
            InitializeComponent();

            this.TreeView.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(TreeView_MouseLeftButtonDown), true);
        }

        [Import]
        internal ClientServersViewModel ViewModel
        {
            get { return this.DataContext as ClientServersViewModel; }
            set { this.DataContext = value; }
        }

        private void TreeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (this.ViewModel == null) return;

            var frameworkElement = e.OriginalSource as FrameworkElement;
            if (frameworkElement != null)
            {
                var target = TreeHelper.FindAncestor(frameworkElement, d =>
                {
                    var s = d as StackPanel;
                    return s != null && s.Name == "Part_TreeViewItem" && s.DataContext != null && (s.DataContext is ClientInfo || s.DataContext is ServerInfo);
                });

                var f = target as FrameworkElement;
                if (f != null)
                    this.ViewModel.RequestFreshData(f.DataContext);
            }
        }
    }
}
